#include <unistd.h>
#include "common.h"

void parser(char *buf)
{
    unsigned long long inode=0;
    unsigned char key[HASHKEYLEN];
    static unsigned char path[MAXFILEPATH];
    static unsigned char i,j,k;
    
    while(*buf)
    {
	if( *buf == '\n' )
	{
	  while(*++buf && *buf == ' ');
	  if( *buf == '/' || *buf == '.' )
	     i=0;

	  //clear cache
	  j=MAXFILEPATH;
	  while(j-i)path[--j]='\0';
	  inode=k=0;
	}

	if(!i)
	{
	    for(; *buf && *buf != '\n' ; path[j++]=*buf++);

	    if(*buf == '\n')
	    {
		i=j--;
		path[j]='/'; //replacing ':' with '/' or path is incomplete
	    }
	}
	else
	{
	    if ( !k )
	    {
		while( *buf && *buf >= '0' && *buf <= '9')
		    inode = inode*10 + *buf++ - '0';

		if( *buf == ' ') //surpass space
		{
		    k=1;
		    buf++;
		}
	    }

	    for(; *buf && *buf != '\n' ;path[j++]=*buf++);

	    if(*buf == '\n' && inode && !MDFile(path,key))
		ht_insert(key,inode);
	}
    }
}

char *gcmd;

int main(int argc,char **argv)
{
   char buf[MAXBUFSIZE];
   int fd[2];
   pipe(fd);
   unsigned short b;
   if(argc !=2 )
   {
	printf("usage:\v lsdup <dir>\n");
	return 0;
   }
   gcmd=argv[1];
   switch(fork())
   {
	case 0:
	// just get file list, even hidden ones
	    close(fd[0]);	//close read end
	    dup2(fd[1],1);	//dup stdout with fd[1]
	    execlp("ls","ls","-iRAB1",argv[1],0);

	//if successful,anything below will never execute
	    perror("execlp");
	    _exit(1);
	case -1:
	    perror("fork");
	    break;
	default:
	    close(fd[1]);	//close write end
	    while(( b = read(fd[0],buf,MAXBUFSIZE)) > 0 )
	    {
		buf[b]=0;
		parser(buf);
	        while(b)buf[--b]='\0';
	    }
        ht_list_dups();
   }
   return 0;
}
